迭代：

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<TreeNode*> T;
        std::vector<int> res;
        while(root || !T.empty()) {
            while(root) {
                T.push_back(root);
                res.push_back(root->val);
                root = root->left;
            }
            if ( !T.empty())
            {
                root = T.back();
                T.pop_back();
                root = root->right;
            }
        }
        return res;
    }
};

递归：
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void print(TreeNode* root, vector<int> &res) {
        if (root) {
            res.push_back(root->val);
            print(root->left, res);
            print(root->right, res);
        }
        
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        print(root, res);
        return res;
    }
};